/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JIFUsuario.java
 *
 * Created on 25/07/2011, 14:54:21
 */
package view.admin;

import control.PessoaControl;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.text.MaskFormatter;
import model.EntidadeSimpleFactory;
import model.Email;
import model.Pessoa;
import util.Conversor;
import util.ValidadorCPF;
import view.IJIFSimpleFactory;

/**
 *
 * @author Felipe
 */


public class JIFPessoa extends JInternalFrame implements IJIFSimpleFactory {

    private PessoaControl controller;    
    private boolean alterar, alterado;
    private int id;
    private MaskFormatter mskCpf, mskDtNasc, mskEmissor;
    private static byte[] fotoEstatica;
    private Vector<Email> associados;          
    
    /** Creates new form JIFUsuario */
    public JIFPessoa() {
        id =0;        
        controller = PessoaControl.getInstance();
        alterar = false;
        initComponents();        
        txtBusca.setFocusable(true);
        selecionarAba(0);
    }

    /** m
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jTabbedPane1 = new javax.swing.JTabbedPane();
        pnlLista = new javax.swing.JPanel();
        pnlSuperior = new javax.swing.JPanel();
        pnlBusca = new javax.swing.JPanel();
        cbbBusca = new javax.swing.JComboBox();
        btnBuscar = new javax.swing.JButton();
        txtBusca = new javax.swing.JTextField();
        pnlJtb = new javax.swing.JPanel();
        jtbSuperior = new javax.swing.JToolBar();
        btnIncluir = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        btnRemover = new javax.swing.JButton();
        btnAssociarEmail = new javax.swing.JButton();
        pnlSuperiorCentro = new javax.swing.JPanel();
        pnlSuperiorCentroDivisor = new javax.swing.JPanel();
        pnlSul = new javax.swing.JPanel();
        pnlLeste = new javax.swing.JPanel();
        pnlOeste = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        pnlCadBasico = new javax.swing.JPanel();
        pnlCamposCadastro = new javax.swing.JPanel();
        lblNome = new javax.swing.JLabel();
        lblLogin = new javax.swing.JLabel();
        lblSenha = new javax.swing.JLabel();
        lblTipo = new javax.swing.JLabel();
        txtNome = new javax.swing.JTextField();
        txtLogin = new javax.swing.JTextField();
        cbbTipo = new javax.swing.JComboBox();
        ptxtSenha = new javax.swing.JPasswordField();
        txtRg = new javax.swing.JTextField();
        lblCpf = new javax.swing.JLabel();
        lblRg = new javax.swing.JLabel();
        lblEmissor = new javax.swing.JLabel();
        cbbUf = new javax.swing.JComboBox();
        try
        {
            // Cria o formato da mascara
            mskCpf = new MaskFormatter("###.###.###-##");  

            // Define o tipo de caracter onde será inserido o texto
            mskCpf.setPlaceholderCharacter('_');
        }   
        catch (ParseException excp)
        {
        }
        ftxtCpf = new JFormattedTextField(mskCpf);
        lblUf = new javax.swing.JLabel();
        lblObservacao = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txaObservacao = new javax.swing.JTextArea();
        lblDtNasci = new javax.swing.JLabel();
        try
        {
            // Cria o formato da mascara
            mskDtNasc = new MaskFormatter("##/##/####");  

            // Define o tipo de caracter onde será inserido o texto
            mskDtNasc.setPlaceholderCharacter('_');
        }   
        catch (ParseException excp)
        {
        }
        ftxtDtNasc = new JFormattedTextField(mskDtNasc);  ;
        lblFoto = new javax.swing.JLabel();
        btnProcurarFoto = new javax.swing.JButton();
        btnLimparFoto = new javax.swing.JButton();
        txtEmissor = new javax.swing.JTextField();
        btnMostrarSenha = new javax.swing.JButton();
        cbxAtivo = new javax.swing.JCheckBox();
        pnlBotoes = new javax.swing.JPanel();
        btnGravar = new javax.swing.JButton();
        btnVoltar = new javax.swing.JButton();
        pnlFotoLeste = new javax.swing.JPanel();
        pnlFoto = new javax.swing.JPanel();
        lblFotoImagem = new javax.swing.JLabel();
        pnlEmails = new javax.swing.JPanel();
        pnlEmailCentro = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        lblEmailsAssociados = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        lstEmailsAssociados = new javax.swing.JList();
        jbtnAssociarEmail = new javax.swing.JButton();
        pnlEmailBotoes = new javax.swing.JPanel();
        btnEmailVoltar = new javax.swing.JButton();
        btnEmailGravar = new javax.swing.JButton();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setIconifiable(true);
        setTitle("Cadastro de usuarios");
        setPreferredSize(new java.awt.Dimension(765, 582));
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        pnlLista.setLayout(new java.awt.BorderLayout());

        pnlSuperior.setMinimumSize(new java.awt.Dimension(364, 50));
        pnlSuperior.setPreferredSize(new java.awt.Dimension(613, 50));
        pnlSuperior.setLayout(new java.awt.BorderLayout());

        pnlBusca.setLayout(new javax.swing.BoxLayout(pnlBusca, javax.swing.BoxLayout.LINE_AXIS));

        cbbBusca.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nome", "Login", "Tipo de usuário" }));
        cbbBusca.setMaximumSize(new java.awt.Dimension(200, 20));
        cbbBusca.setMinimumSize(new java.awt.Dimension(200, 20));
        cbbBusca.setPreferredSize(new java.awt.Dimension(200, 20));
        pnlBusca.add(cbbBusca);

        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/i16x16/buscar2.png"))); // NOI18N
        btnBuscar.setToolTipText("Procurar");
        btnBuscar.setMaximumSize(new java.awt.Dimension(30, 20));
        btnBuscar.setMinimumSize(new java.awt.Dimension(30, 20));
        btnBuscar.setOpaque(false);
        btnBuscar.setPreferredSize(new java.awt.Dimension(30, 20));
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });
        pnlBusca.add(btnBuscar);

        txtBusca.setMaximumSize(new java.awt.Dimension(200, 20));
        txtBusca.setMinimumSize(new java.awt.Dimension(200, 20));
        txtBusca.setPreferredSize(new java.awt.Dimension(200, 20));
        txtBusca.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtBuscaKeyPressed(evt);
            }
        });
        pnlBusca.add(txtBusca);

        pnlSuperior.add(pnlBusca, java.awt.BorderLayout.EAST);

        pnlJtb.setLayout(new java.awt.BorderLayout());

        jtbSuperior.setBorder(null);
        jtbSuperior.setFloatable(false);
        jtbSuperior.setRollover(true);
        jtbSuperior.setOpaque(false);

        btnIncluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/i16x16/inserir.png"))); // NOI18N
        btnIncluir.setToolTipText("Incluir registro");
        btnIncluir.setFocusable(false);
        btnIncluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnIncluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jtbSuperior, org.jdesktop.beansbinding.ELProperty.create("false"), btnIncluir, org.jdesktop.beansbinding.BeanProperty.create("borderPainted"));
        bindingGroup.addBinding(binding);

        btnIncluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIncluirActionPerformed(evt);
            }
        });
        jtbSuperior.add(btnIncluir);

        btnAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/i16x16/alterar.png"))); // NOI18N
        btnAlterar.setToolTipText("Alterar registro");
        btnAlterar.setFocusable(false);
        btnAlterar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAlterar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jtbSuperior, org.jdesktop.beansbinding.ELProperty.create("false"), btnAlterar, org.jdesktop.beansbinding.BeanProperty.create("borderPainted"));
        bindingGroup.addBinding(binding);

        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });
        jtbSuperior.add(btnAlterar);

        btnRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/i16x16/remover.png"))); // NOI18N
        btnRemover.setToolTipText("Remover registro");
        btnRemover.setFocusable(false);
        btnRemover.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnRemover.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jtbSuperior, org.jdesktop.beansbinding.ELProperty.create("false"), btnRemover, org.jdesktop.beansbinding.BeanProperty.create("borderPainted"));
        bindingGroup.addBinding(binding);

        btnRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoverActionPerformed(evt);
            }
        });
        jtbSuperior.add(btnRemover);

        btnAssociarEmail.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/i16x16/email5.png"))); // NOI18N
        btnAssociarEmail.setToolTipText("Associar email");
        btnAssociarEmail.setFocusable(false);
        btnAssociarEmail.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAssociarEmail.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jtbSuperior, org.jdesktop.beansbinding.ELProperty.create("false"), btnAssociarEmail, org.jdesktop.beansbinding.BeanProperty.create("borderPainted"));
        bindingGroup.addBinding(binding);

        btnAssociarEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAssociarEmailActionPerformed(evt);
            }
        });
        jtbSuperior.add(btnAssociarEmail);

        pnlJtb.add(jtbSuperior, java.awt.BorderLayout.CENTER);

        pnlSuperior.add(pnlJtb, java.awt.BorderLayout.WEST);

        pnlSuperiorCentro.setLayout(new javax.swing.BoxLayout(pnlSuperiorCentro, javax.swing.BoxLayout.LINE_AXIS));

        pnlSuperiorCentroDivisor.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        pnlSuperiorCentroDivisor.setMaximumSize(new java.awt.Dimension(1000, 20));
        pnlSuperiorCentroDivisor.setOpaque(false);
        pnlSuperiorCentroDivisor.setPreferredSize(new java.awt.Dimension(1000, 20));
        pnlSuperiorCentro.add(pnlSuperiorCentroDivisor);

        pnlSuperior.add(pnlSuperiorCentro, java.awt.BorderLayout.CENTER);

        pnlLista.add(pnlSuperior, java.awt.BorderLayout.PAGE_START);
        pnlLista.add(pnlSul, java.awt.BorderLayout.SOUTH);
        pnlLista.add(pnlLeste, java.awt.BorderLayout.LINE_END);
        pnlLista.add(pnlOeste, java.awt.BorderLayout.LINE_START);

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(controller.getTableModel());
        jTable1.setRowHeight(20);
        ajustarTamanhoColunas();
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTable1KeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        pnlLista.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jTabbedPane1.addTab("Lista", pnlLista);

        pnlCadBasico.setLayout(new java.awt.BorderLayout());

        lblNome.setText("Nome");

        lblLogin.setText("Login");

        lblSenha.setText("Senha");

        lblTipo.setText("Tipo de usuário");

        txtNome.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtNomeCaretUpdate(evt);
            }
        });
        txtNome.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtNomeFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtNomeFocusLost(evt);
            }
        });
        txtNome.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtNomeKeyPressed(evt);
            }
        });

        txtLogin.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtLoginCaretUpdate(evt);
            }
        });
        txtLogin.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtLoginFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtLoginFocusLost(evt);
            }
        });
        txtLogin.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtLoginKeyPressed(evt);
            }
        });

        cbbTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "ADMINISTRADOR", "TECNICO", "USUARIO" }));
        cbbTipo.setName(""); // NOI18N
        cbbTipo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                cbbTipoMousePressed(evt);
            }
        });

        ptxtSenha.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                ptxtSenhaCaretUpdate(evt);
            }
        });
        ptxtSenha.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                ptxtSenhaFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                ptxtSenhaFocusLost(evt);
            }
        });
        ptxtSenha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                ptxtSenhaKeyPressed(evt);
            }
        });

        txtRg.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtRgCaretUpdate(evt);
            }
        });
        txtRg.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtRgFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtRgFocusLost(evt);
            }
        });
        txtRg.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtRgKeyPressed(evt);
            }
        });

        lblCpf.setText("CPF");

        lblRg.setText("RG");

        lblEmissor.setText("Emissor");

        cbbUf.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "AC", "AL", "AM", "AP", "BA", "CE", "DF", "ES", "GO", "MA", "MG", "MS", "MT", "PA", "PB", "PE", "PI", "PR", "RJ", "RN", "RO", "RR", "RS", "SC", "SE", "SP", "TO" }));
        cbbUf.setName(""); // NOI18N
        cbbUf.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                cbbUfMousePressed(evt);
            }
        });

        ftxtCpf.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        ftxtCpf.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                ftxtCpfCaretUpdate(evt);
            }
        });
        ftxtCpf.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                ftxtCpfFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                ftxtCpfFocusLost(evt);
            }
        });
        ftxtCpf.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                ftxtCpfKeyPressed(evt);
            }
        });

        lblUf.setText("UF");

        lblObservacao.setText("Observação");

        txaObservacao.setColumns(20);
        txaObservacao.setLineWrap(true);
        txaObservacao.setRows(5);
        txaObservacao.setWrapStyleWord(true);
        txaObservacao.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txaObservacaoFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txaObservacaoFocusLost(evt);
            }
        });
        txaObservacao.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txaObservacaoKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(txaObservacao);

        lblDtNasci.setText("Data de Nascimento");

        formatador1 = new SimpleDateFormat("dd/MM/yyyy");
        formatador1.setLenient(false);
        formatador2 = new SimpleDateFormat("ddMMyyyy");
        ftxtDtNasc.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        ftxtDtNasc.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                ftxtDtNascCaretUpdate(evt);
            }
        });
        ftxtDtNasc.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                ftxtDtNascFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                ftxtDtNascFocusLost(evt);
            }
        });
        ftxtDtNasc.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                ftxtDtNascKeyPressed(evt);
            }
        });

        lblFoto.setText("Foto");

        btnProcurarFoto.setText("Procurar");
        btnProcurarFoto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnProcurarFotoActionPerformed(evt);
            }
        });

        btnLimparFoto.setText("Limpar");
        btnLimparFoto.setToolTipText("Exclui a foto cadastrada");
        btnLimparFoto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimparFotoActionPerformed(evt);
            }
        });

        txtEmissor.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtEmissorCaretUpdate(evt);
            }
        });
        txtEmissor.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtEmissorFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtEmissorFocusLost(evt);
            }
        });
        txtEmissor.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtEmissorKeyPressed(evt);
            }
        });

        btnMostrarSenha.setText("Mostrar");
        btnMostrarSenha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMostrarSenhaActionPerformed(evt);
            }
        });

        cbxAtivo.setText("Ativo");
        cbxAtivo.setToolTipText("Este campo informa se o funcionário está atualmente trabalhando na empresa");

        javax.swing.GroupLayout pnlCamposCadastroLayout = new javax.swing.GroupLayout(pnlCamposCadastro);
        pnlCamposCadastro.setLayout(pnlCamposCadastroLayout);
        pnlCamposCadastroLayout.setHorizontalGroup(
            pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlCamposCadastroLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblObservacao)
                    .addComponent(lblNome)
                    .addComponent(lblLogin)
                    .addComponent(lblSenha)
                    .addComponent(lblCpf)
                    .addComponent(lblRg)
                    .addComponent(lblDtNasci)
                    .addComponent(lblTipo)
                    .addComponent(lblFoto))
                .addGap(18, 18, 18)
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ftxtDtNasc, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(pnlCamposCadastroLayout.createSequentialGroup()
                        .addComponent(cbbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(cbxAtivo))
                    .addGroup(pnlCamposCadastroLayout.createSequentialGroup()
                        .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(ftxtCpf, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtRg, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE))
                        .addGap(39, 39, 39)
                        .addComponent(lblEmissor)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtEmissor, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblUf)
                        .addGap(18, 18, 18)
                        .addComponent(cbbUf, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(pnlCamposCadastroLayout.createSequentialGroup()
                        .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(ptxtSenha, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtLogin, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addComponent(btnMostrarSenha))
                    .addGroup(pnlCamposCadastroLayout.createSequentialGroup()
                        .addComponent(btnProcurarFoto)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnLimparFoto, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(114, Short.MAX_VALUE))
        );
        pnlCamposCadastroLayout.setVerticalGroup(
            pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlCamposCadastroLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNome)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblLogin)
                    .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblSenha)
                    .addComponent(ptxtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnMostrarSenha))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ftxtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblCpf))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtRg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblRg)
                    .addComponent(lblEmissor)
                    .addComponent(lblUf)
                    .addComponent(cbbUf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtEmissor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ftxtDtNasc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblDtNasci))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblFoto)
                    .addComponent(btnProcurarFoto)
                    .addComponent(btnLimparFoto))
                .addGap(12, 12, 12)
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblTipo)
                    .addComponent(cbbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbxAtivo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlCamposCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblObservacao)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(153, Short.MAX_VALUE))
        );

        pnlCadBasico.add(pnlCamposCadastro, java.awt.BorderLayout.CENTER);

        pnlBotoes.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        btnGravar.setText("Gravar");
        btnGravar.setEnabled(false);
        btnGravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGravarActionPerformed(evt);
            }
        });

        btnVoltar.setText("Voltar");
        btnVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVoltarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlBotoesLayout = new javax.swing.GroupLayout(pnlBotoes);
        pnlBotoes.setLayout(pnlBotoesLayout);
        pnlBotoesLayout.setHorizontalGroup(
            pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlBotoesLayout.createSequentialGroup()
                .addContainerGap(613, Short.MAX_VALUE)
                .addComponent(btnGravar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnVoltar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        pnlBotoesLayout.setVerticalGroup(
            pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlBotoesLayout.createSequentialGroup()
                .addGroup(pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnVoltar)
                    .addComponent(btnGravar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pnlCadBasico.add(pnlBotoes, java.awt.BorderLayout.PAGE_END);

        pnlFoto.setBorder(javax.swing.BorderFactory.createTitledBorder("Foto 3x4"));
        pnlFoto.setToolTipText("Foto");
        pnlFoto.setPreferredSize(new java.awt.Dimension(150, 180));
        pnlFoto.setLayout(new java.awt.BorderLayout());
        pnlFoto.add(lblFotoImagem, java.awt.BorderLayout.CENTER);

        pnlFotoLeste.add(pnlFoto);

        pnlCadBasico.add(pnlFotoLeste, java.awt.BorderLayout.LINE_END);

        jTabbedPane1.addTab("Informações básicas", pnlCadBasico);

        pnlEmails.setLayout(new java.awt.BorderLayout());

        lblEmailsAssociados.setText("E-mails associados");

        lstEmailsAssociados.setToolTipText("Clique duas vezes sobre um registro para desassocia-lo deste usuário ");
        lstEmailsAssociados.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lstEmailsAssociadosMouseClicked(evt);
            }
        });
        lstEmailsAssociados.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                lstEmailsAssociadosKeyPressed(evt);
            }
        });
        jScrollPane4.setViewportView(lstEmailsAssociados);

        jbtnAssociarEmail.setText("jButton1");
        jbtnAssociarEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAssociarEmailActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblEmailsAssociados)
                .addGap(22, 22, 22)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnAssociarEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(15, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtnAssociarEmail)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblEmailsAssociados))
                .addContainerGap(31, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout pnlEmailCentroLayout = new javax.swing.GroupLayout(pnlEmailCentro);
        pnlEmailCentro.setLayout(pnlEmailCentroLayout);
        pnlEmailCentroLayout.setHorizontalGroup(
            pnlEmailCentroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlEmailCentroLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(381, Short.MAX_VALUE))
        );
        pnlEmailCentroLayout.setVerticalGroup(
            pnlEmailCentroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlEmailCentroLayout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(217, Short.MAX_VALUE))
        );

        pnlEmails.add(pnlEmailCentro, java.awt.BorderLayout.CENTER);

        pnlEmailBotoes.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        pnlEmailBotoes.setPreferredSize(new java.awt.Dimension(724, 47));

        btnEmailVoltar.setText("Voltar");
        btnEmailVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEmailVoltarActionPerformed(evt);
            }
        });

        btnEmailGravar.setText("Gravar");
        btnEmailGravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEmailGravarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlEmailBotoesLayout = new javax.swing.GroupLayout(pnlEmailBotoes);
        pnlEmailBotoes.setLayout(pnlEmailBotoesLayout);
        pnlEmailBotoesLayout.setHorizontalGroup(
            pnlEmailBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlEmailBotoesLayout.createSequentialGroup()
                .addContainerGap(609, Short.MAX_VALUE)
                .addComponent(btnEmailGravar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEmailVoltar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18))
        );
        pnlEmailBotoesLayout.setVerticalGroup(
            pnlEmailBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlEmailBotoesLayout.createSequentialGroup()
                .addGroup(pnlEmailBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnEmailGravar)
                    .addComponent(btnEmailVoltar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pnlEmails.add(pnlEmailBotoes, java.awt.BorderLayout.PAGE_END);

        jTabbedPane1.addTab("E-mails associados", pnlEmails);

        getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER);

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGravarActionPerformed
        if (!isAlterar()) {
            gravarPessoa();
        } else {
            alterarPessoa();
        }               
    }//GEN-LAST:event_btnGravarActionPerformed

    private void txtNomeCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtNomeCaretUpdate
        liberarBtnGravar();
    }//GEN-LAST:event_txtNomeCaretUpdate

    private void txtLoginCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtLoginCaretUpdate
        liberarBtnGravar();
    }//GEN-LAST:event_txtLoginCaretUpdate

    private void ptxtSenhaCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_ptxtSenhaCaretUpdate
        liberarBtnGravar();
    }//GEN-LAST:event_ptxtSenhaCaretUpdate

    private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverActionPerformed
        removerPessoa();                       
    }//GEN-LAST:event_btnRemoverActionPerformed

    private void btnIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIncluirActionPerformed
       selecionarAba(1);
       setAlterar(false);
    }//GEN-LAST:event_btnIncluirActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        popularCampos();
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        buscar();
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void txtBuscaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscaKeyPressed
         if (evt.getKeyCode() == evt.VK_ENTER) {                      
             buscar();
         }  
    }//GEN-LAST:event_txtBuscaKeyPressed

private void ftxtCpfCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_ftxtCpfCaretUpdate
    liberarBtnGravar();
}//GEN-LAST:event_ftxtCpfCaretUpdate

private void txtRgCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtRgCaretUpdate
    liberarBtnGravar();
}//GEN-LAST:event_txtRgCaretUpdate

private void ftxtDtNascCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_ftxtDtNascCaretUpdate
    liberarBtnGravar();
}//GEN-LAST:event_ftxtDtNascCaretUpdate

private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
    if(evt.getClickCount() == 2){
          popularCampos();
    }
}//GEN-LAST:event_jTable1MouseClicked

    private void btnProcurarFotoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnProcurarFotoActionPerformed
        setAlterado(true);
        final JFileChooser fc = new JFileChooser();
        //In response to a button click:
        int retorno = fc.showOpenDialog(null);
            
        if (retorno == JFileChooser.APPROVE_OPTION) {
            
            File file = fc.getSelectedFile();
           
            try {
                setFotoEstatica(Conversor.getBytesFromFile(file));
                ImageIcon imageIcon = Conversor.getImageIconFromByte(getFotoEstatica());
                lblFotoImagem.setIcon(imageIcon);
            } catch (Exception ex) {
                setFotoEstatica(null);
                Logger.getLogger(JIFPessoa.class.getName()).log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(null, "Ocorreu um erro ao inserir a imagem!\n"+
                                "Caso o erro ocorra novamente, entre em contato com o programador.");
            }           
        }                
    }//GEN-LAST:event_btnProcurarFotoActionPerformed

    private void btnLimparFotoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimparFotoActionPerformed
        setAlterado(true);
        try {
            setFotoEstatica(null);
            lblFotoImagem.setIcon(null);
        } catch (Exception ex) {
            Logger.getLogger(JIFPessoa.class.getName()).log(Level.SEVERE, null, ex);
        }     
        
    }//GEN-LAST:event_btnLimparFotoActionPerformed

    private void txtNomeFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtNomeFocusGained
        txtNome.setBackground(new Color(255,255,220));
    }//GEN-LAST:event_txtNomeFocusGained

    private void txtNomeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtNomeFocusLost
        txtNome.setBackground(new Color(255,255,255));
    }//GEN-LAST:event_txtNomeFocusLost

    private void txtLoginFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtLoginFocusGained
        txtLogin.setBackground(new Color(255,255,220));
    }//GEN-LAST:event_txtLoginFocusGained

    private void txtLoginFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtLoginFocusLost
        txtLogin.setBackground(new Color(255,255,255));
    }//GEN-LAST:event_txtLoginFocusLost

    private void ptxtSenhaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ptxtSenhaFocusGained
        ptxtSenha.setBackground(new Color(255,255,220));
    }//GEN-LAST:event_ptxtSenhaFocusGained

    private void ptxtSenhaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ptxtSenhaFocusLost
        ptxtSenha.setBackground(new Color(255,255,255));
    }//GEN-LAST:event_ptxtSenhaFocusLost

    private void ftxtCpfFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ftxtCpfFocusGained
        ftxtCpf.setBackground(new Color(255,255,220));
    }//GEN-LAST:event_ftxtCpfFocusGained

    private void ftxtCpfFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ftxtCpfFocusLost
        ftxtCpf.setBackground(new Color(255,255,255));
    }//GEN-LAST:event_ftxtCpfFocusLost

    private void txtRgFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtRgFocusGained
        txtRg.setBackground(new Color(255,255,220));
    }//GEN-LAST:event_txtRgFocusGained

    private void txtRgFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtRgFocusLost
        txtRg.setBackground(new Color(255,255,255));
    }//GEN-LAST:event_txtRgFocusLost

    private void ftxtDtNascFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ftxtDtNascFocusGained
        ftxtDtNasc.setBackground(new Color(255,255,220));
    }//GEN-LAST:event_ftxtDtNascFocusGained

    private void ftxtDtNascFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ftxtDtNascFocusLost
        ftxtDtNasc.setBackground(new Color(255,255,255));
    }//GEN-LAST:event_ftxtDtNascFocusLost

    private void txaObservacaoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txaObservacaoFocusGained
        txaObservacao.setBackground(new Color(255,255,220));
    }//GEN-LAST:event_txaObservacaoFocusGained

    private void txaObservacaoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txaObservacaoFocusLost
        txaObservacao.setBackground(new Color(255,255,255));
    }//GEN-LAST:event_txaObservacaoFocusLost

    private void btnVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVoltarActionPerformed
        mudarFrame();
    }//GEN-LAST:event_btnVoltarActionPerformed

    private void txtNomeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNomeKeyPressed
        setAlterado(true);
    }//GEN-LAST:event_txtNomeKeyPressed

    private void txtLoginKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtLoginKeyPressed
        setAlterado(true);
    }//GEN-LAST:event_txtLoginKeyPressed

    private void ptxtSenhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ptxtSenhaKeyPressed
        setAlterado(true);
    }//GEN-LAST:event_ptxtSenhaKeyPressed

    private void ftxtCpfKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ftxtCpfKeyPressed
        setAlterado(true);
    }//GEN-LAST:event_ftxtCpfKeyPressed

    private void txtRgKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtRgKeyPressed
        setAlterado(true);
    }//GEN-LAST:event_txtRgKeyPressed

    private void ftxtDtNascKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ftxtDtNascKeyPressed
        setAlterado(true);
    }//GEN-LAST:event_ftxtDtNascKeyPressed

    private void txaObservacaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txaObservacaoKeyPressed
        setAlterado(true);
    }//GEN-LAST:event_txaObservacaoKeyPressed

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
         if (getAlterado()) {
            int n = JOptionPane.showConfirmDialog(null,
                    "Deseja gravar as alterações efetuadas!",
                    "Confirmação",
                    JOptionPane.YES_NO_CANCEL_OPTION);
        
            if (n != JOptionPane.CANCEL_OPTION) {
                if (n == JOptionPane.YES_OPTION) {
                    alterarPessoa();
                    dispose();
                } else {
                    dispose();
                }
            }             
        } else {
            dispose();
        }             
    }//GEN-LAST:event_formInternalFrameClosing

    private void cbbUfMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cbbUfMousePressed
        setAlterado(true);
    }//GEN-LAST:event_cbbUfMousePressed

    private void cbbTipoMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cbbTipoMousePressed
        setAlterado(true);
    }//GEN-LAST:event_cbbTipoMousePressed

    private void btnAssociarEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAssociarEmailActionPerformed
        Pessoa pessoa = null;
        int id = 0;
        id = controller.getTableModel().getIdAt(getLinha());
        try {
            pessoa = controller.getPessoa(id);
        } catch (Exception ex) {
            Logger.getLogger(JIFPessoa.class.getName()).log(Level.SEVERE, null, ex);
        }
        selecionarAba(2);
        carregarEmails(pessoa, controller.getListEmail());
        
    }//GEN-LAST:event_btnAssociarEmailActionPerformed

    private void txtEmissorCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtEmissorCaretUpdate
        liberarBtnGravar();
    }//GEN-LAST:event_txtEmissorCaretUpdate

    private void txtEmissorFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtEmissorFocusGained
        txtEmissor.setBackground(new Color(255,255,220));
    }//GEN-LAST:event_txtEmissorFocusGained

    private void txtEmissorFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtEmissorFocusLost
        txtEmissor.setBackground(new Color(255,255,255));
    }//GEN-LAST:event_txtEmissorFocusLost

    private void txtEmissorKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtEmissorKeyPressed
        setAlterado(true);
    }//GEN-LAST:event_txtEmissorKeyPressed

    private void btnEmailGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEmailGravarActionPerformed
        Pessoa pessoa = controller.getTableModel().getPessoa(getLinha());
        pessoa.setEmails(associados);
        try {
            controller.alterarPessoa(pessoa);
            JOptionPane.showMessageDialog(null, "Registro salvo com sucesso!");
            selecionarAba(0);
            setAlterado(false);
        } catch (Exception ex) {
            Logger.getLogger(JDAssociarPessoaAEmail.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Ocorreu um erro ao tentar salvar o email!\n" +
                                            ex.getMessage());
        }        
    }//GEN-LAST:event_btnEmailGravarActionPerformed

    private void lstEmailsAssociadosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstEmailsAssociadosMouseClicked
        if (evt.getClickCount() == 2) {
           rmEmailFromLista();                     
       }
    }//GEN-LAST:event_lstEmailsAssociadosMouseClicked

    private void btnEmailVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEmailVoltarActionPerformed
        mudarFrame();
    }//GEN-LAST:event_btnEmailVoltarActionPerformed

    private void jbtnAssociarEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAssociarEmailActionPerformed
        Pessoa pessoa = null;
        int id = 0 ;
        id = controller.getTableModel().getIdAt(getLinha());
        try {
            pessoa = controller.getPessoa(id);
        } catch (Exception ex) {
            Logger.getLogger(JIFPessoa.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        JDAssociarEmailAPessoa associar = new JDAssociarEmailAPessoa(null, true, pessoa,
                                                controller.getListEmail()); 
        associados = new Vector<Email>();
        for (int k = 0; k < pessoa.getEmails().size(); k++) {
            associados.add(pessoa.getEmails().get(k));
        }
        lstEmailsAssociados.setListData(associados); 
        selecionarAba(0);
    }//GEN-LAST:event_jbtnAssociarEmailActionPerformed

    private void btnMostrarSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMostrarSenhaActionPerformed
        JOptionPane.showMessageDialog(null, ptxtSenha.getText());
    }//GEN-LAST:event_btnMostrarSenhaActionPerformed

    private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyPressed
        switch (evt.getKeyCode()) {
            case KeyEvent.VK_ENTER  : popularCampos();
                                      break;
            case KeyEvent.VK_DELETE : removerPessoa();
                                      break;        
        }
    }//GEN-LAST:event_jTable1KeyPressed

    private void lstEmailsAssociadosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_lstEmailsAssociadosKeyPressed
        if (evt.getKeyCode() == evt.VK_DELETE) {                      
             rmEmailFromLista();
         }
    }//GEN-LAST:event_lstEmailsAssociadosKeyPressed
    
    private void mudarFrame() {
        if (getAlterado()) {
            int n = JOptionPane.showConfirmDialog(null,
                    "Deseja gravar as alterações efetuadas!",
                    "Confirmação",
                    JOptionPane.YES_NO_CANCEL_OPTION);
        
            if (n != JOptionPane.CANCEL_OPTION) {
                if (n == JOptionPane.YES_OPTION) {
                    alterarPessoa();
                    setAlterar(false);
                    setAlterado(false);
                } else {
                    selecionarAba(0);
                    setAlterado(false);
                    limparCampos();
                }
            }             
        } else {
            limparCampos();            
            selecionarAba(0);            
        }       
    }    
    
    private void buscar() {
        controller.buscar(txtBusca.getText(), cbbBusca.getSelectedIndex());
    }
    /**
     * Este método foi feito para facilitar a leitura do código.<br>
     * Ele retorna o índice da linha orientado a zero e em qualquer ordem de apresentação.
     * @return int linha selecionada  
     */
    private int getLinha() {
        return jTable1.convertRowIndexToModel(jTable1.getSelectedRow());
    }
    
    private void limparCampos() {
        txtNome.setText("");
        txtLogin.setText("");
        ptxtSenha.setText("");
        cbbTipo.setSelectedIndex(0);
        ftxtCpf.setText("");
        txtRg.setText("");
        txtEmissor.setText("");
        cbbUf.setSelectedItem("");
        ftxtDtNasc.setText("");
        txaObservacao.setText("");
        cbxAtivo.setSelected(false);
        lblFotoImagem.setIcon(null);
    }
    
    private void popularCampos() {
        Pessoa pessoa = controller.getTableModel().getPessoa(getLinha());
        txtNome.setText(pessoa.getNome());
        txtLogin.setText(pessoa.getLogin());
        ptxtSenha.setText(pessoa.getSenha());
        cbbTipo.setSelectedItem(pessoa.getTipo());
        ftxtCpf.setText(pessoa.getCpf());
        txtRg.setText(pessoa.getRg());
        txtEmissor.setText(pessoa.getEmissor());
        cbbUf.setSelectedItem(pessoa.getUf());        
        ftxtDtNasc.setText(formatador2.format(pessoa.getDataNascimento().getTime()));
        txaObservacao.setText(pessoa.getObservacao());
        if (pessoa.isAtivo()) {
            cbxAtivo.setSelected(true);
        } else {
            cbxAtivo.setSelected(false);            
        }
        
        try {
            lblFotoImagem.setIcon(Conversor.getImageIconFromByte(pessoa.getFoto()));
        } catch (Exception ex) {
            Logger.getLogger(JIFPessoa.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            setFotoEstatica(pessoa.getFoto());
        }
        
        setId(pessoa.getId());
        setAlterar(true);
        selecionarAba(1);
    }
    
        
    private void liberarBtnGravar() {
        if (
                (txtNome.getText().length() > 0 ) && 
                (txtLogin.getText().length() > 0) &&
                (ptxtSenha.getText().length() > 0) &&
                (!ftxtCpf.getText().endsWith("_")) &&               
                (txtRg.getText().length() > 0) &&
                (txtEmissor.getText().length() > 0) &&
                (!ftxtDtNasc.getText().endsWith("_")) 
            ) 
        {
            btnGravar.setEnabled(true);
        } else
        {
            btnGravar.setEnabled(false);
        }       
    }
    
    private Pessoa atualizarPessoa(Pessoa pessoa) throws Exception  {
        // Atualiza o objeto
        pessoa.setNome(txtNome.getText());
        pessoa.setLogin(txtLogin.getText());
        pessoa.setSenha(ptxtSenha.getText());
        pessoa.setTipo((String)cbbTipo.getSelectedItem());

        //TODO Aplicar quando entrar em produção
        
        if (ValidadorCPF.validarCPF(ftxtCpf.getText())) {
            pessoa.setCpf(ftxtCpf.getText());
        } else {
            throw new Exception("Cpf Inválido!");
        }        
        
        
        //pessoa.setCpf(ftxtCpf.getText());
        
        pessoa.setRg(txtRg.getText());
        pessoa.setEmissor(txtEmissor.getText());
        pessoa.setUf((String)cbbUf.getSelectedItem().toString());
        pessoa.setObservacao(txaObservacao.getText());
        
        if (cbxAtivo.isSelected()) {
            pessoa.setAtivo(true);
        } else {
            pessoa.setAtivo(false);
        }
     
        try {
            Date data = formatador1.parse(ftxtDtNasc.getText());
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(data);
            pessoa.setDataNascimento(calendar);
        } catch (ParseException ex) {
           throw new Exception("Data inconsistente!");
        }
        try {
            pessoa.setFoto(getFotoEstatica());
        } catch(Exception e) {
            e.printStackTrace();
            throw new Exception("Houve um erro ao atualizar a foto");            
        } finally {
            setAlterado(false);
            setFotoEstatica(null);
        }       
        return pessoa;
        
    }
    private void gravarPessoa() {
        try {
            Pessoa pessoa = (Pessoa) EntidadeSimpleFactory.getEntity(Pessoa.class);
            controller.addPessoa(atualizarPessoa(pessoa));
            JOptionPane.showMessageDialog(null, "Registro gravado com sucesso!");
            limparCampos();
            selecionarAba(0);
            setAlterar(false);            
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }   
    
    private void alterarPessoa() {
        try {                        
            controller.alterarPessoa(atualizarPessoa(controller.getDAO().get(getId())));            
            setAlterar(false);
            
            setId(0);
            JOptionPane.showMessageDialog(null, "Registro alterado com sucesso!");            
            selecionarAba(0);
            limparCampos();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }                
                
    private void removerPessoa() {
        int n = JOptionPane.showConfirmDialog(null,
                    "Esta operação não poderá ser desfeita!\nDeseja realmente excluir este registro?\n",
                    "Exclusão de registro",
                    JOptionPane.YES_NO_OPTION);
        
        if (n == JOptionPane.YES_OPTION) {
            try {
                controller.removerUsuario(getLinha());
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            }
        }        
    }    
    
    private void carregarEmails(Pessoa pessoa, List<Email> todosEmails) {
        
        // Cria um vetor de pessoas. Ele será usado para demonstrar as pessoas que
        // serão associadas. Para isso é preciso verificar as pessoas que já estão associadas.
        associados = new Vector<Email>();
        for (int k = 0; k < pessoa.getEmails().size(); k++) {
            associados.add(pessoa.getEmails().get(k));
        }
        lstEmailsAssociados.setListData(associados);               
    }            
    
    private void rmEmailFromLista() {
        Email email = (Email)lstEmailsAssociados.getSelectedValue();
        associados.remove(email);
        lstEmailsAssociados.removeAll();
        lstEmailsAssociados.setListData(associados);
        setAlterado(true);
    }      
    
    
    private void ajustarTamanhoColunas() {
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(250);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(120);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(120);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(120);
    }
    
    private void selecionarAba(int aba) {
        switch (aba) {
            case 0 :    jTabbedPane1.setSelectedIndex(0);
                        jTabbedPane1.setEnabledAt(0, true);
                        jTabbedPane1.setEnabledAt(1, false);
                        jTabbedPane1.setEnabledAt(2, false);
                        break;
                
            case 1 :    jTabbedPane1.setSelectedIndex(1); 
                        txtNome.requestFocus();
                        jTabbedPane1.setEnabledAt(0, false);
                        jTabbedPane1.setEnabledAt(1, true);
                        jTabbedPane1.setEnabledAt(2, false);
                        break;
            
            case 2 :    jTabbedPane1.setSelectedIndex(2);
                        jTabbedPane1.setEnabledAt(0, false);
                        jTabbedPane1.setEnabledAt(1, false);
                        jTabbedPane1.setEnabledAt(2, true);
                        break;
        }
    }
            
    // Getters and setters
    private void setAlterar(boolean alterar) { this.alterar = alterar; }
    private boolean isAlterar() { return this.alterar; }
    private void setId(int id) { this.id = id; }
    private int getId() { return this.id; }
    private void setAlterado(boolean alterado) { this.alterado = alterado; }
    private boolean getAlterado() { return this.alterado; }

    private void setFotoEstatica(byte[] foto) {
        this.fotoEstatica = foto;
    }
    
    private byte[] getFotoEstatica() {
        return fotoEstatica;
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnAssociarEmail;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnEmailGravar;
    private javax.swing.JButton btnEmailVoltar;
    private javax.swing.JButton btnGravar;
    private javax.swing.JButton btnIncluir;
    private javax.swing.JButton btnLimparFoto;
    private javax.swing.JButton btnMostrarSenha;
    private javax.swing.JButton btnProcurarFoto;
    private javax.swing.JButton btnRemover;
    private javax.swing.JButton btnVoltar;
    private javax.swing.JComboBox cbbBusca;
    private javax.swing.JComboBox cbbTipo;
    private javax.swing.JComboBox cbbUf;
    private javax.swing.JCheckBox cbxAtivo;
    private javax.swing.JFormattedTextField ftxtCpf;
    private SimpleDateFormat formatador1, formatador2;
    private javax.swing.JFormattedTextField ftxtDtNasc;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton jbtnAssociarEmail;
    private javax.swing.JToolBar jtbSuperior;
    private javax.swing.JLabel lblCpf;
    private javax.swing.JLabel lblDtNasci;
    private javax.swing.JLabel lblEmailsAssociados;
    private javax.swing.JLabel lblEmissor;
    private javax.swing.JLabel lblFoto;
    private javax.swing.JLabel lblFotoImagem;
    private javax.swing.JLabel lblLogin;
    private javax.swing.JLabel lblNome;
    private javax.swing.JLabel lblObservacao;
    private javax.swing.JLabel lblRg;
    private javax.swing.JLabel lblSenha;
    private javax.swing.JLabel lblTipo;
    private javax.swing.JLabel lblUf;
    private javax.swing.JList lstEmailsAssociados;
    private javax.swing.JPanel pnlBotoes;
    private javax.swing.JPanel pnlBusca;
    private javax.swing.JPanel pnlCadBasico;
    private javax.swing.JPanel pnlCamposCadastro;
    private javax.swing.JPanel pnlEmailBotoes;
    private javax.swing.JPanel pnlEmailCentro;
    private javax.swing.JPanel pnlEmails;
    private javax.swing.JPanel pnlFoto;
    private javax.swing.JPanel pnlFotoLeste;
    private javax.swing.JPanel pnlJtb;
    private javax.swing.JPanel pnlLeste;
    private javax.swing.JPanel pnlLista;
    private javax.swing.JPanel pnlOeste;
    private javax.swing.JPanel pnlSul;
    private javax.swing.JPanel pnlSuperior;
    private javax.swing.JPanel pnlSuperiorCentro;
    private javax.swing.JPanel pnlSuperiorCentroDivisor;
    private javax.swing.JPasswordField ptxtSenha;
    private javax.swing.JTextArea txaObservacao;
    private javax.swing.JTextField txtBusca;
    private javax.swing.JTextField txtEmissor;
    private javax.swing.JTextField txtLogin;
    private javax.swing.JTextField txtNome;
    private javax.swing.JTextField txtRg;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
         
 }